<template>
  <div class="analysis">
    <a-row style="margin-top: 0" :gutter="[24, 24]">
     <a-col :sm="24" :md="12" :xl="6">
        <chart-card
          :loading="loading"
          :title="$t('设备总数')"
          :total="totalThings"
        >
          <a-tooltip :title="totalThings" slot="action">
            <a-icon type="info-circle-o" />
          </a-tooltip>
          <div slot="footer">
            <a-space
              >服务器<span>{{ serviceCount }}</span>
              <a @click="getAllToExcel">设备数量</a><span>{{ devCount }}</span>
            </a-space>
          </div>
        </chart-card>
      </a-col>
      <a-col :sm="24" :md="12" :xl="6">
        <chart-card
          :loading="loading"
          :title="$t('设备在线率')"
          :total="onlinePercent"
        >
          <div>
            <mini-progress
              target="90"
              :percent="onlinePercent"
              color="#13C2C2"
              height="8px"
            />
          </div>
          <div slot="footer">
            <a-space>
              <a @click="queryOnline">在线设备</a
              ><span>{{ onlineCount }}</span> 设备总数<span>{{
                totalThings
              }}</span>
            </a-space>
          </div>
        </chart-card>
      </a-col>

      <a-col :sm="24" :md="12" :xl="6">
        <chart-card :title="$t('实时告警数')" :total="activeAlarm">
          <div>
            <mini-area :data="alarms" />
          </div>
          <div slot="footer">
            <a-space>
              无告警设备数量<span>{{ noAlarmDevCount }}</span>
            </a-space>
          </div>
        </chart-card>
      </a-col>
      <a-space>
        <a-button v-if="timerID" @click="stopTimer()">停止定时器</a-button>
        <a-button v-else @click="beginTimer()">启动定时器</a-button>
        <a-button @click="getInfo()">刷新数据</a-button>
      <a-button @click="calNow()">实时分析</a-button>
      </a-space>
      <p></p>
      <a-space v-if="isEdge">
        运维服务地址:<a-input v-model="svrAddr"></a-input>
        <a-button @click="tunnel">开启运维</a-button>
        <a-button @click="reboot">重新启动</a-button>
      </a-space>
    </a-row>
    <a-card
      :loading="loading"
      style="margin-top: 24px"
      :bordered="false"
      :body-style="{ padding: '24px' }"
    >
      <div class="salesCard">
        <a-tabs
          default-active-key="1"
          size="large"
          :tab-bar-style="{ marginBottom: '24px', paddingLeft: '16px' }"
        >
          <a-tab-pane :tab="$t('实时告警分布图')" key="1">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar :title="$ta('告警类型', 'p')" :data="alarmByType" />
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <ranking-list :title="$ta('告警类型', 'p')" :list="rankList" />
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>
    <a-row style="margin: 0 -12px">
      <a-col
        style="padding: 0 12px"
        :xl="12"
        :lg="24"
        :md="24"
        :sm="24"
        :xs="24"
      >
        <a-card
          :loading="loading"
          :bordered="false"
          style="margin-top: 24px"
          :title="$t('服务运行状态')"
        >
          <hot-search ref="hotSearch" />
        </a-card>
      </a-col>
      <a-col
        style="padding: 0 12px"
        :xl="12"
        :lg="24"
        :md="24"
        :sm="24"
        :xs="24"
      >
        <a-card
          :loading="loading"
          :bordered="false"
          style="margin-top: 24px"
          :title="$t('设备类型分布图')"
        >
          <sales-data :sourceData="devTypes" />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { getEx, postEx } from "@/services/crud";
import ChartCard from "@/components/card/ChartCard";
//import MiniArea from "@/components/chart/MiniArea";
//import MiniBar from "@/components/chart/MiniBar";
import MiniProgress from "@/components/chart/MiniProgress";
import Bar from "@/components/chart/Bar";
import RankingList from "@/components/chart/RankingList";
import HotSearch from "./HotSearch";
import SalesData from "./SalesData";
//import Trend from "@/components/chart/Trend";
import MiniArea from "@/components/chart/MiniArea.vue";
import { getThingsOnline, getThings,getAllThings } from "@/services/things";
import XLSX from "xlsx";
export default {
  name: "Analysis",
  //i18n: require('./i18n'),
  computed: {
    isEdge() {
      return process.env.VUE_APP_TYPE === "edge";
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //因为当钩子执行前，组件实例还没被创建
      // vm 就是当前组件的实例相当于上面的 this，所以在 next 方法里你就可以把 vm 当 this 来用了。
      console.log(vm); //当前组件的实例
      //vm.beginTimer();
    });
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    this.stopTimer();
    next();
  },
  data() {
    return {
      rankList: [],
      loading: false,
      totalThings: 1000,
      serviceCount: 100,
      devCount: 200,
      onlineCount: 100,
      currentInfo: null,
      offlineCount: 100,
      onlinePercent: 100,
      activeAlarm: 100,
      alarms: [],
      noAlarmDevCount: 0,
      alarmByType: [],
      devTypes: [],
      force: false,
      timerID: null,
      svrAddr: "42.192.199.243:39999",
    };
  },
  created() {
    this.getInfo();
    //this.beginTimer();
  },
  methods: {
    getAllToExcel() {
      getAllThings().then((res) => {
        const ws = XLSX.utils.json_to_sheet(res);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "all");
        XLSX.writeFile(wb, "all.xlsx");
      });
    },
    reboot() {
      postEx("maintain/hreboot");
    },
    beginTimer() {
    const self = this;
      if (this.timerID) {
        clearInterval(this.timerID);
        this.timerID = null;
      }
      this.timerID = setInterval(() => {
      self.getInfo();
    }, 60 * 1000 * 5);
      if (this.$refs.hotSearch) {
        this.$refs.hotSearch.beginTimer();
      }
    },
    stopTimer() {
      clearInterval(this.timerID);
      this.timerID = null;
      if (this.$refs.hotSearch) {
        this.$refs.hotSearch.stopTimer();
      }
    },
    calNow() {
      let self = this;
      postEx("/system").finally(() => {
        self.getInfo();
      });
    },
    tunnel() {
      if (this.svrAddr) {
        let ip;
        let port;
        let parts = this.svrAddr.split(":");
        if (parts && parts.length == 2) {
          ip = parts[0];
          port = parts[1];
        }
        postEx("/maintain/tunnel/", { ip: ip, port: Number(port) });
      }
  },
    queryOnline() {
      getThingsOnline().then((res) => {
        const ws = XLSX.utils.json_to_sheet(res);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "online");
        XLSX.writeFile(wb, "online.xlsx");
      });
    },
    getInfo() {
      const self = this;
      getEx("/system").then((res) => {
        if (res && res.data && res.data.result) {
          let result = res.data.result;
          if (result.length > 0) {
            result.forEach((r) => {
              let alarmCount =
                r.result &&
                r.result["by_alarm"] &&
                r.result["by_alarm"].length > 0
                  ? r.result["by_alarm"][0].count
                  : 0;
              let alarmInfo = { x: r.calc_time, y: alarmCount };
              self.alarms.push(alarmInfo);
            });
            let lastone = result[result.length - 1].result;
            let count = 0;
            let devCount = 0;
            let serviceCount = 0;
            this.currentInfo = lastone;
            let models = lastone["by_model"];
            self.devTypes = [];
            if (models) {
              models.forEach((m) => {
                if (!m.is_station) {
                  devCount += m.count;
                  count += m.count;
                  self.devTypes.push({ item: m.s_name, count: m.count });
                }

              });
            }
            self.totalThings = count;

            let catalogs = lastone["by_catalog"];
            if (catalogs) {
              catalogs.forEach((c) => {
                if (c.s_name == "服务") {
                  serviceCount += c.count;
                }
              });
              self.serviceCount = serviceCount;
            }
            self.devCount = self.totalThings - self.serviceCount;

            let state = lastone["by_state"];
            if (state) {
              state.forEach((s) => {
                if (s) {
                  if (s.state == 1) {
                    self.onlineCount = s.count;
                    self.offlineCount = this.totalThings - s.count;
                  } else {
                    self.onlineCount = this.totalThings - s.count;
                    self.offlineCount = s.count;
                  }
                }
              });
              self.onlinePercent =
                ((self.onlineCount * 100) / self.totalThings).toFixed(2) + "%";
            }
            let alarmState = lastone["by_alarm"];
            self.activeAlarm =
              alarmState && alarmState.length > 0 ? alarmState[0].count : 0;

            self.noAlarmDevCount =
              lastone["by_no_alarm"] && lastone["by_no_alarm"].length > 0
                ? lastone["by_no_alarm"][0].count
                : 0;
            let alarmByType = lastone["by_alarm_type"];
            if (alarmByType) {
              self.alarmByType = [];
              self.rankList = [];
              alarmByType.forEach((t) => {
                self.alarmByType.push({ x: t.alarm_name, y: t.count });
                self.rankList.push({ name: t.alarm_name, total: t.count });
              });
            }
            //let models = lastone["by_model"]
          }
        }
      });
    },
  },
  components: {
    //Trend,
    SalesData,
    HotSearch,
    RankingList,
    Bar,
    MiniProgress,
    //MiniBar,
    //MiniArea,
    ChartCard,
    MiniArea,
  },
};
</script>

<style lang="less" scoped>
.extra-wrap {
  .extra-item {
    display: inline-block;
    margin-right: 24px;
    a:not(:first-child) {
      margin-left: 24px;
    }
  }
}
@media screen and (max-width: 992px) {
  .extra-wrap .extra-item {
    display: none;
  }
}
@media screen and (max-width: 576px) {
  .extra-wrap {
    display: none;
  }
}
</style>